package com.zl.csMall.code.config.token;

import com.zl.csMall.code.LoginCacheMap;
import com.zl.csMall.util.Util;
import com.zl.csMall.vo.ReturnModel;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @description: AOP TOKEN校验切面
 * @author: ChenNing
 * @date 2025-10-15 11:02
 */
@Aspect
@Component
public class TokenAspect {

    private final LoginCacheMap loginCacheMap;

    public TokenAspect(LoginCacheMap loginCacheMap) {
        this.loginCacheMap = loginCacheMap;
    }

    // 定义切入点，拦截戴有 @TokenTriggerAspect 的方法
    @Pointcut("@annotation(com.zl.csMall.code.config.token.TokenTriggerAspect)")
    public void methodsAnnotatedWithTriggerAspect(){}

    @Around("methodsAnnotatedWithTriggerAspect()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        // 切面开始执行，方法参数数组：joinPoint.getArgs()
        boolean proceed = executeRepeatedLogic(joinPoint.getArgs());
        if (!proceed) {
            // token校验失败
            return new ReturnModel(false, "token校验失败！");
        }
        try {
            Object result = joinPoint.proceed();
            executePostLogic();
            return result;
        } catch (Throwable throwable) {
            throw throwable;
        }
    }

    private boolean executeRepeatedLogic(Object[] args) {
        // 实现重复逻辑检查，检查用户是否已经执行过类似操作，防止重复提交等
        boolean condition = checkCondition(args);
        return condition;
    }

    private void executePostLogic() {
        // 实现你的后置逻辑，例如日志记录、通知等
    }

    private boolean checkCondition(Object[] args) {
        // token校验
        String token = String.valueOf(args[0]);
        // 测试TOKEN：q1w2e3r4t5y6u7i8o9p0a1s2d3f4g5h6j7k8l9
        if ("q1w2e3r4t5y6u7i8o9p0a1s2d3f4g5h6j7k8l9".equals(token)){
            return true;
        }
        return Util.verifyRandomToken(loginCacheMap, token);
    }

}
